<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>websocket通讯</title>
</head>

<body>
<p>【socket开启者的ID信息】<div><input id="userId" name="userId" type="text" value="10"></div>
<p>【客户端向服务器发送的内容】<div><input id="toUserId" name="toUserId" type="text" value="20">
    <input id="contentText" name="contentText" type="text" value="hello websocket"></div>
<p>【操作】<div><button onclick="sendMessage()">发送消息</button></div>
</body>

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
	var userId = $("#userId").val()

    var websocket = null;
    if ('WebSocket' in window) {
		// 实际开发可以传token,由后台解析出用户信息
        websocket = new WebSocket('ws://localhost:8080/webSocket/' + userId);
        // websocket = new WebSocket('ws://pfyzkd.natappfree.cc/sell/webSocket');
    } else {
        alert('该浏览器不支持websocket!');
    }

    websocket.onopen = function (event) {
        console.log('websocket建立连接');
    }

    websocket.onclose = function (event) {
        console.log('websocket连接关闭');
    }

    websocket.onmessage = function (event) {
		//将消息显示在网页上
		alert('收到消息:' + event.data)
        console.log('收到消息:' + event.data)
    }

    websocket.onerror = function () {
        alert('websocket通信发生错误！');
    }

    window.onbeforeunload = function () {
        websocket.close();
    }


    function sendMessage() {
        websocket.send('{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}');
        console.log('{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}');
    }
</script>

</html>
